<template>
  <div class="editor-blog">
    <el-form :inline="true" :model="blogForm" :rules="blogRules" class="demo-form-inline" ref="form">
      <el-form-item label="所属模块" prop="module">
        <el-input v-model="blogForm.module" placeholder="所属模块"></el-input>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="blogForm.title" placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="blogForm.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="(data,index) in statusOptions"
            :key="index"
            :label="data.label"
            :value="data.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <mavon-editor v-model="blogForm.content" style="width: 100%;height: 100%" :ishljs="true" :codeStyle="code_style"
                  ref="md" @imgAdd="$imgAdd" @imgDel="$imgDel"/>
    <div class="btn-center">
      <el-button type="primary" @click="submit" round>提交</el-button>
    </div>
  </div>
</template>

<script>
  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import Blog from "@/api/blog/blog";

  export default {
    name: "EditorBlog",
    data() {
      const validate = (rule, value, callback) => {
        if (value.length <= 0) {
          callback(new Error('不能为空！'))
        } else {
          callback()
        }
      };
      return {
        isUpdate: false,
        code_style: 'rainbow',
        blogForm: {
          id: undefined,
          module: undefined,
          title: undefined,
          content: undefined,
          status: 1
        },
        // 状态数据字典
        statusOptions: [
          {
            value: 1,
            label: '发布'
          },
          {
            value: 0,
            label: '草稿'
          }
        ],
        blogRules: {
          module: [{required: true, trigger: 'blur', validator: validate}],
          title: [{required: true, trigger: 'blur', validator: validate}],
          content: [{required: true, trigger: 'blur', validator: validate}]
        },
      }
    },
    components: {
      mavonEditor
    },
    created() {
      let id = this.$route.query.id;
      if (id !== undefined && id !== null) {
        Blog.getById(id).then(res => {
          this.blogForm = res.data;
          this.isUpdate = true;
        }).catch(err => {
          this.isUpdate = false;
          console.log(err);
        })
      } else {
        this.isUpdate = false;
      }
    },
    methods: {
      $imgAdd(pos, $file) {
        // 第一步.将图片上传到服务器.
        let formData = new FormData();
        formData.append('image', $file);
        this.img_file[pos] = $file;
        request({
          url: 'api/upload',
          method: 'post',
          data: formData,
          headers: {'Content-Type': 'multipart/form-data'}
        }).then(res => {
          let _res = res.data;
          // 第二步.将返回的url替换到文本原位置[外链图片转存失败(img-Anv63SQR-1564734760257)(0)] -> [外链图片转存失败(img-OVX7vZS4-1564734760259)(url)]
          this.$refs.md.$img2Url(pos, _res.msg)
        }).catch(err => {
          console.log(err);
        })
      },
      $imgDel(pos) {
        delete this.img_file[pos];
      },
      submit() {
        this.$refs.form.validate(valid => {
          if (!valid || this.blogForm.content === '') {
            this.$message({
              message: '内容不能为空！',
              type: 'warning'
            });
          } else {
            if (this.isUpdate) {
              Blog.updateById(this.blogForm).then(res => {
                if (res.code === 200) {
                  this.$message({
                    message: '更新成功',
                    type: 'success'
                  });
                  this.$router.push({name: 'Blog'});
                } else {
                  this.$message({
                    message: res.msg || '更新失败',
                    type: 'error'
                  })
                }
                console.log(res);
              }).catch(err => {
                this.$message({
                  message: '更新失败',
                  type: 'error'
                });
                console.log(err);
              })
            } else {
              Blog.save(this.blogForm).then(res => {
                if (res.code === 200) {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  });
                  this.$router.push({name: 'Blog'});
                } else {
                  this.$message({
                    message: res.msg || '添加失败',
                    type: 'error'
                  })
                }
                console.log(res);
              }).catch(err => {
                this.$message({
                  message: '添加失败',
                  type: 'error'
                });
                console.log(err);
              })
            }
          }
        });
      }
    }
  }
</script>

<style lang="scss">
  .editor-blog {
    margin-left: 5px;
    margin-top: 10px;
  }

  .btn-center {
    margin: auto;
    padding-top: 10px;
    text-align: center;
  }
</style>
